/*
 * @Descripttion: 公共封装文件
 * @version: 电子名片2.0
 * @Author: 冯健
 * @Date: 2020-12-03 14:10:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-24 15:09:21
 */

import { MessageBox } from 'element-ui'
import { export_json_to_excel } from '@/utils/Export2Excel'

/**
 * @Author: 冯健
 * @LastEditTime: 冯健
 * @msg: 对异步处理;成功失败都会返回2个值，异步函数时就不需要使用try catch
 * @param {*} apiFun 异步方法
 * @param {*} parasm 异步参数
 * @return {*} 返回异步结果res 成功 err失败
 */
export function asyncApiFun(apiFun, ...parasm) {
  return apiFun(...parasm).then(res => [res, null]).catch(err => [null, err])
}
// 导出数据
export function exportList(config, data) {
  // console.log(data)
  // 设置标题
  const tHeader = config

  let _data = []
  // 数据处理
  
  data.forEach(element => {
     _data.push(Object.values(element))
  });
  
  // console.log(_data)
  export_json_to_excel(tHeader, _data, 'excel')
}

/**
 * @Author: 冯健
 * @LastEditTime: 冯健
 * @msg: MessageBox 弹框
 * @param {*} options.content 提示内容
 * @param {*} options.title 提示标题
 * @param {*} options.confirm 确认按钮
 * @param {*} options.cancel 取消按钮
 * @param {*} callBack 回调函数
 * @return {*}
 */
export function openMessageBox(options, callBack) {
  MessageBox.confirm(options.content, options.title || '提示', {
    distinguishCancelAndClose: true,
    confirmButtonText: options.confirm || '确定',
    cancelButtonText: options.cancel || '取消',
    closeOnClickModal: false
  }).then(() => callBack(true)).catch(action => action === 'cancel' && callBack(false))
}

/**
 * @msg: 编辑弹窗数据初始化
 */
export function initEditList(editList, detail, form2) {
  const _detail = detail || {}
  const _form = {}
  const _form2 = {}
  let _obj = null
  editList.forEach(item => {
    _form[item.key] = _detail[item.key]
    if (item.key1) _form[item.key1] = _detail[item.key1]
  })
  if (form2) {
    Object.keys(form2).forEach(key => {
      _form2[key] = _detail[key]
    })
    _obj = { _form, _form2 }
  }
  return _obj || _form
}

export function isNumber(num) {
  num = Number(num)
  let _statu = true
  if (isNaN(num) || num < 1) {
    _statu = false
  }
  return _statu
}
export function getDay(day, date) {
  let today
  if (date) today = new Date(date)
  else today = new Date()
  const targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
  today.setTime(targetday_milliseconds) // 注意，这行是关键代码
  const tYear = today.getFullYear()
  let tMonth = today.getMonth()
  let tDate = today.getDate()
  tMonth = doHandleMonth(tMonth + 1)
  tDate = doHandleMonth(tDate)
  return tYear + '-' + tMonth + '-' + tDate
}
function doHandleMonth(month) {
  let m = month
  if (month.toString().length === 1) {
    m = '0' + month
  }
  return m
}
